<template>
  <div class="app-container">
    <el-form
      :model="form"
      :rules="rules"
      ref="userRef"
      label-width="160px"
      :label-position="isPhone ? 'top' : 'left'"
    >
      <el-collapse v-model="activeCollapseItems" accordion>
        <!-- 基本信息 -->
        <el-collapse-item title="基本信息" name="basic">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                v-if="form.userId == undefined"
                label="账号"
                prop="userName"
              >
                <el-input
                  v-model="form.userName"
                  placeholder="请输入账号"
                  maxlength="30"
                  :disabled="isDetailMode"
                  :readonly="isFieldReadonly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                v-if="form.userId == undefined"
                label="密码"
                prop="password"
              >
                <el-input
                  v-model="form.password"
                  placeholder="请输入密码"
                  type="password"
                  maxlength="20"
                  show-password
                  :readonly="isFieldReadonly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名" prop="nickName">
                <el-input
                  v-model="form.nickName"
                  placeholder="请输入姓名"
                  maxlength="30"
                  :disabled="!isFieldEditable('nickName')"
                  :readonly="isFieldReadonly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-radio-group
                  v-model="form.sex"
                  :disabled="!isFieldEditable('sex') || isDetailMode"
                >
                  <el-radio
                    v-for="dict in sys_user_sex"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="民族" prop="nation">
                <el-select
                  filterable
                  v-model="form.nation"
                  placeholder="请选择民族"
                  style="width: 100%"
                  :disabled="!isFieldEditable('nation') || isDetailMode"
                >
                  <el-option
                    v-for="dict in nation"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证号" prop="idCard">
                <el-input
                  v-model="form.idCard"
                  placeholder="请输入身份证号"
                  maxlength="18"
                  :disabled="!isFieldEditable('idCard')"
                  :readonly="isFieldReadonly"
                  @blur="handleIdCardChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phonenumber">
                <el-input
                  v-model="form.phonenumber"
                  placeholder="请输入手机号码"
                  maxlength="11"
                  :disabled="!isFieldEditable('phonenumber')"
                  :readonly="isFieldReadonly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input
                  v-model="form.email"
                  placeholder="请输入邮箱"
                  maxlength="50"
                  :disabled="!isFieldEditable('email')"
                  :readonly="isFieldReadonly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="籍贯" prop="origin">
                <el-input
                  v-model="form.origin"
                  placeholder="请输入籍贯"
                  maxlength="50"
                  :disabled="!isFieldEditable('origin')"
                  :readonly="isFieldReadonly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="政治面貌" prop="political">
                <el-select
                  v-model="form.political"
                  placeholder="请选择政治面貌"
                  style="width: 100%"
                  :disabled="!isFieldEditable('political') || isDetailMode"
                >
                  <el-option
                    v-for="dict in political_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生日期" prop="birthday">
                <el-input
                  disabled
                  v-model="previewBirthday"
                  placeholder="根据身份证号自动计算"
                  readonly
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年龄" prop="age">
                <el-input
                  disabled
                  v-model="previewAge"
                  placeholder="根据身份证号自动计算"
                  readonly
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="紧急联系人" prop="emergencyContact">
                <el-input
                  v-model="form.emergencyContact"
                  placeholder="请输入紧急联系人"
                  maxlength="20"
                  :disabled="!isFieldEditable('emergencyContact')"
                  :readonly="isFieldReadonly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="紧急联系人联系方式"
                prop="emergencyPhonenumber"
              >
                <el-input
                  v-model="form.emergencyPhonenumber"
                  placeholder="请输入紧急联系人电话"
                  maxlength="11"
                  :disabled="!isFieldEditable('emergencyPhonenumber')"
                  :readonly="isFieldReadonly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="家庭住址" prop="address">
                <el-input
                  v-model="form.address"
                  placeholder="请输入家庭住址"
                  :readonly="isFieldReadonly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="照片" prop="avatar">
                <image-upload
                  v-model="form.avatar"
                  :limit="1"
                  :fileSize="50"
                  :fileType="['png', 'jpg', 'jpeg']"
                  :disabled="!isFieldEditable('avatar')"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 工程硕博士试点项目信息 -->
        <el-collapse-item title="工程硕博士试点项目信息" name="train">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工程硕博士培养领域" prop="trainField">
                <el-select
                  v-model="form.trainField"
                  placeholder="请选择培养领域"
                  style="width: 100%"
                  :disabled="!isFieldEditable('trainField') || isDetailMode"
                >
                  <el-option
                    v-for="dict in specialty"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程硕博士培养类别" prop="trainType">
                <el-select
                  v-model="form.trainType"
                  placeholder="请选择培养类别"
                  style="width: 100%"
                  :disabled="!isFieldEditable('trainType') || isDetailMode"
                >
                  <el-option
                    v-for="dict in training_category"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程硕博士高校名称" prop="trainUniversity">
                <el-select
                  v-model="form.trainUniversity"
                  placeholder="请选择高校名称"
                  style="width: 100%"
                  filterable
                  :disabled="
                    !isFieldEditable('trainUniversity') || isDetailMode
                  "
                >
                  <el-option
                    v-for="dict in university"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程硕博士学院名称" prop="trainCollege">
                <el-input
                  v-model="form.trainCollege"
                  placeholder="请输入学院名称"
                  maxlength="100"
                  :disabled="!isFieldEditable('trainCollege')"
                  :readonly="isFieldReadonly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程硕博士培养专业" prop="trainMajor">
                <el-input
                  v-model="form.trainMajor"
                  placeholder="请输入培养专业"
                  maxlength="100"
                  :disabled="!isFieldEditable('trainMajor')"
                  :readonly="isFieldReadonly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程硕博士入学时间" prop="trainStartDate">
                <el-date-picker
                  v-model="form.trainStartDate"
                  type="date"
                  placeholder="选择入学时间"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  :disabled="!isFieldEditable('trainStartDate') || isDetailMode"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="研究生学制" prop="trainYear">
                <el-select
                  v-model="form.trainYear"
                  placeholder="请选择学制"
                  style="width: 100%"
                  :disabled="!isFieldEditable('trainYear') || isDetailMode"
                >
                  <el-option
                    v-for="dict in graduate_education_system"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="工程硕博士生计划毕业时间"
                prop="trainStartEnd"
              >
                <el-date-picker
                  v-model="form.trainStartEnd"
                  type="date"
                  placeholder="选择毕业时间"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  :disabled="!isFieldEditable('trainStartEnd') || isDetailMode"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="当前处于培养阶段" prop="trainStatus">
                <el-select
                  v-model="form.trainStatus"
                  placeholder="请选择培养阶段"
                  style="width: 100%"
                  :disabled="!isFieldEditable('trainStatus') || isDetailMode"
                >
                  <el-option
                    v-for="dict in train_progress"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="毕业后是否留在中国一汽工作"
                prop="graduateStay"
              >
                <el-radio-group
                  v-model="form.graduateStay"
                  :disabled="!isFieldEditable('graduateStay') || isDetailMode"
                >
                  <el-radio
                    v-for="dict in sys_yes_no"
                    :key="dict.value"
                    :label="dict.value"
                    >{{ dict.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 本科学历信息 -->
        <el-collapse-item title="本科学历信息" name="graduate">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="本科毕业高校名称" prop="graduateUniversity">
                <el-select
                  v-model="form.graduateUniversity"
                  placeholder="请选择本科高校名称"
                  style="width: 100%"
                  filterable
                  :disabled="
                    !isFieldEditable('graduateUniversity') || isDetailMode
                  "
                >
                  <el-option
                    v-for="dict in university"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="本科毕业学院名称" prop="graduateCollege">
                <el-input
                  v-model="form.graduateCollege"
                  placeholder="请输入本科学院名称"
                  maxlength="100"
                  :disabled="!isFieldEditable('graduateCollege')"
                  :readonly="isFieldReadonly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="本科专业" prop="graduateMajor">
                <el-input
                  v-model="form.graduateMajor"
                  placeholder="请输入本科专业"
                  maxlength="100"
                  :disabled="!isFieldEditable('graduateMajor')"
                  :readonly="isFieldReadonly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="本科毕业时间" prop="graduateStartEnd">
                <el-date-picker
                  v-model="form.graduateStartEnd"
                  type="date"
                  placeholder="选择本科毕业时间"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  :disabled="
                    !isFieldEditable('graduateStartEnd') || isDetailMode
                  "
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 研究生学历信息（只有在职博士填写） -->
        <el-collapse-item
          v-if="form.trainType === 'on-the-job_doctor'"
          title="研究生学历信息（只有在职博士填写）"
          name="master"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="研究生毕业高校名称" prop="masterUniversity">
                <el-select
                  v-model="form.masterUniversity"
                  placeholder="请选择研究生高校名称"
                  style="width: 100%"
                  filterable
                  :disabled="
                    !isFieldEditable('masterUniversity') || isDetailMode
                  "
                >
                  <el-option
                    v-for="dict in university"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="研究生毕业学院名称" prop="masterCollege">
                <el-input
                  v-model="form.masterCollege"
                  placeholder="请输入研究生学院名称"
                  maxlength="100"
                  :disabled="!isFieldEditable('masterCollege')"
                  :readonly="isFieldReadonly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="研究生专业" prop="masterMajor">
                <el-input
                  v-model="form.masterMajor"
                  placeholder="请输入研究生专业"
                  maxlength="100"
                  :disabled="!isFieldEditable('masterMajor')"
                  :readonly="isFieldReadonly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="研究生毕业时间" prop="masterStartEnd">
                <el-date-picker
                  v-model="form.masterStartEnd"
                  type="date"
                  placeholder="选择研究生毕业时间"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  :disabled="!isFieldEditable('masterStartEnd') || isDetailMode"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 培养单位管理员和培养部门管理员额外字段 -->
        <el-collapse-item title="实践信息" name="practice">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="培养单位" prop="trainDeptId">
                <el-select
                  v-model="form.trainDeptId"
                  placeholder="请选择培养单位"
                  style="width: 100%"
                  :disabled="!isFieldEditable('trainDeptId') || isDetailMode"
                  @change="handleTrainDeptChange"
                >
                  <el-option
                    v-for="dict in trainingUnitList"
                    :key="dict.deptId"
                    :label="dict.deptName"
                    :value="dict.deptId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="实践部门" prop="practiceDeptId">
                <el-select
                  v-model="form.practiceDeptId"
                  placeholder="请选择实践部门"
                  style="width: 100%"
                  :disabled="!isFieldEditable('practiceDeptId') || isDetailMode"
                >
                  <el-option
                    v-for="dict in practiceDeptList"
                    :key="dict.deptId"
                    :label="dict.deptName"
                    :value="dict.deptId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="实践地点" prop="practiceAddress">
                <el-cascader
                  v-model="form.practiceAddress"
                  :disabled="
                    !isFieldEditable('practiceAddress') || isDetailMode
                  "
                  :options="regionOptions"
                  :props="cascaderProps"
                  placeholder="请选择省市区"
                  style="width: 100%"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入企实践开始时间" prop="joinStartDate">
                <el-date-picker
                  v-model="form.joinStartDate"
                  type="date"
                  placeholder="选择入企实践开始时间"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  :disabled="!isFieldEditable('joinStartDate') || isDetailMode"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入企实践结束时间" prop="joinEntDate">
                <el-date-picker
                  v-model="form.joinEntDate"
                  type="date"
                  placeholder="选择入企实践结束时间"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  :disabled="!isFieldEditable('joinEntDate') || isDetailMode"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入企实践课题名称" prop="joinEntTopicName">
                <el-input
                  v-model="form.joinEntTopicName"
                  placeholder="请输入入企实践课题名称"
                  maxlength="200"
                  :disabled="!isFieldEditable('joinEntTopicName')"
                  :readonly="isFieldReadonly"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="入企实践课题简介"
                prop="joinEntTopicIntroduction"
              >
                <el-input
                  v-model="form.joinEntTopicIntroduction"
                  type="textarea"
                  placeholder="请输入入企实践课题简介"
                  :rows="4"
                  :disabled="!isFieldEditable('joinEntTopicIntroduction')"
                  :readonly="isFieldReadonly"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <template v-if="isDetailMode">
          <!-- 企业导师信息 -->
          <el-collapse-item title="企业导师信息" name="enterpriseTeacher">
            <el-row :gutter="20" v-if="form.mdtUserEnterpriseTeacherODTO">
              <el-col :span="12">
                <el-form-item label="企业导师">
                  <el-input
                    :value="
                      form.mdtUserEnterpriseTeacherODTO.trainEntTeacherUser
                        ?.nickName
                    "
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="企业导师所属部门">
                  <el-input
                    :value="
                      form.mdtUserEnterpriseTeacherODTO.trainEntTeacherUser
                        ?.deptName
                    "
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="企业导师助理">
                  <el-input
                    :value="
                      form.mdtUserEnterpriseTeacherODTO.trainEntAssistantUser
                        ?.nickName
                    "
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="企业导师助理所属部门">
                  <el-input
                    :value="
                      form.mdtUserEnterpriseTeacherODTO.trainEntAssistantUser
                        ?.deptName
                    "
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="培养单位管理员">
                  <el-input
                    :value="
                      form.mdtUserEnterpriseTeacherODTO.trainOrgUser?.nickName
                    "
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="培养单位管理员所属部门">
                  <el-input
                    :value="
                      form.mdtUserEnterpriseTeacherODTO.trainOrgUser?.deptName
                    "
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="培养部门管理员">
                  <el-input
                    :value="
                      form.mdtUserEnterpriseTeacherODTO.trainDepUser?.nickName
                    "
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="培养部门管理员所属部门">
                  <el-input
                    :value="
                      form.mdtUserEnterpriseTeacherODTO.trainDepUser?.deptName
                    "
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-empty v-else description="暂无企业导师信息" />
          </el-collapse-item>

          <!-- 高校导师信息 -->
          <el-collapse-item title="高校导师信息" name="schoolTeacher">
            <el-row :gutter="20" v-if="form.mdtUserSchoolTeacherODTO">
              <el-col :span="12">
                <el-form-item label="高校导师">
                  <el-input
                    :value="
                      form.mdtUserSchoolTeacherODTO.schoolTeacherUser?.nickName
                    "
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="高校导师所属学校">
                  <el-input
                    :value="
                      form.mdtUserSchoolTeacherODTO.schoolTeacherUser?.deptName
                    "
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-empty v-else description="暂无高校导师信息" />
          </el-collapse-item>

          <!-- 入企实践管理 -->
          <el-collapse-item title="入企实践管理" name="enterpriseManage">
            <el-row :gutter="20" v-if="form.mdtUserEnterpriseManageODTO">
              <el-col :span="12">
                <el-form-item label="入企开始时间">
                  <el-input
                    :value="form.mdtUserEnterpriseManageODTO.joinEntStartDate"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="实践课题">
                  <el-input
                    :value="form.mdtUserEnterpriseManageODTO.joinEntTopicName"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="完成入企手续">
                  <el-input
                    :value="
                      form.mdtUserEnterpriseManageODTO.completeJoinProcedure ===
                      'Y'
                        ? '是'
                        : '否'
                    "
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="完成签署协议">
                  <el-input
                    :value="
                      form.mdtUserEnterpriseManageODTO.completeSignAgreement ===
                      'Y'
                        ? '是'
                        : '否'
                    "
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="完成入职培训">
                  <el-input
                    :value="
                      form.mdtUserEnterpriseManageODTO
                        .completeInductionTrain === 'Y'
                        ? '是'
                        : '否'
                    "
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="完成资源分配">
                  <el-input
                    :value="
                      form.mdtUserEnterpriseManageODTO
                        .completeAllocationResources === 'Y'
                        ? '是'
                        : '否'
                    "
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="完成党转">
                  <el-input
                    :value="
                      form.mdtUserEnterpriseManageODTO.completeTransferParty ===
                      'Y'
                        ? '是'
                        : '否'
                    "
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="住宿安排">
                  <el-input
                    :value="
                      form.mdtUserEnterpriseManageODTO.stayApartment === 'Y'
                        ? '是'
                        : '否'
                    "
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col
                :span="24"
                v-if="
                  form.mdtUserEnterpriseManageODTO.fileObjects &&
                  form.mdtUserEnterpriseManageODTO.fileObjects.length > 0
                "
              >
                <el-form-item label="附件">
                  <div class="file-list">
                    <el-link
                      v-for="file in form.mdtUserEnterpriseManageODTO
                        .fileObjects"
                      :key="file.id"
                      type="primary"
                      :href="file.filePath"
                      target="_blank"
                      style="display: block; margin-bottom: 8px"
                    >
                      {{ file.fileName }}
                    </el-link>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-empty v-else description="暂无入企实践管理信息" />
          </el-collapse-item>

          <!-- 企业实践计划 -->
          <el-collapse-item title="企业实践计划" name="enterprisePlan">
            <el-row :gutter="20" v-if="form.mdtUserEnterprisePlanODTO">
              <el-col :span="12">
                <el-form-item label="论文开始时间">
                  <el-input
                    :value="form.mdtUserEnterprisePlanODTO.thesisStartTime"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="论文中期时间">
                  <el-input
                    :value="form.mdtUserEnterprisePlanODTO.thesisMidTime"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="论文预答辩时间">
                  <el-input
                    :value="form.mdtUserEnterprisePlanODTO.thesisPreTime"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="论文答辩时间">
                  <el-input
                    :value="form.mdtUserEnterprisePlanODTO.thesisEndTime"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col
                :span="24"
                v-if="
                  form.mdtUserEnterprisePlanODTO.planDetails &&
                  form.mdtUserEnterprisePlanODTO.planDetails.length > 0
                "
              >
                <el-form-item label="实践计划详情">
                  <el-table
                    :data="form.mdtUserEnterprisePlanODTO.planDetails"
                    border
                    stripe
                  >
                    <el-table-column
                      prop="planName"
                      label="计划名称"
                      width="120"
                    />
                    <el-table-column
                      prop="planStartTime"
                      label="计划开始时间"
                      width="140"
                    />
                    <el-table-column
                      prop="planEndTime"
                      label="计划结束时间"
                      width="140"
                    />
                    <el-table-column
                      prop="planTarget"
                      label="计划目标"
                      show-overflow-tooltip
                    />
                  </el-table>
                </el-form-item>
              </el-col>
            </el-row>
            <el-empty v-else description="暂无企业实践计划信息" />
          </el-collapse-item>

          <!-- 月度实践进展 -->
          <el-collapse-item title="月度实践进展" name="enterpriseProgress">
            <el-row
              :gutter="20"
              v-if="form.mdtUserEnterpriseProgressODTOList?.length > 0"
            >
              <el-col :span="24">
                <el-table
                  :data="form.mdtUserEnterpriseProgressODTOList"
                  border
                  stripe
                >
                  <el-table-column label="计划名称" width="120">
                    <template #default="scope">
                      {{
                        form.mdtUserEnterprisePlanODTO.planDetails.find(
                          (t) => t.id === scope.row.planDetailId
                        )?.planName
                      }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="planStartTime"
                    label="计划开始时间"
                    width="140"
                  />
                  <el-table-column
                    prop="planEndTime"
                    label="计划结束时间"
                    width="140"
                  />
                  <el-table-column
                    label="计划目标"
                    show-overflow-tooltip
                  >
                    <template #default="scope">
                      {{
                        form.mdtUserEnterprisePlanODTO.planDetails.find(
                          (t) => t.id === scope.row.planDetailId
                        )?.planTarget
                      }}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="100">
                    <template #default="scope">
                      <el-button
                        type="primary"
                        @click="handleGotoProgressDetail(scope.row)"
                        >查看</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
            <el-empty v-else description="暂无月度实践进展信息" />
          </el-collapse-item>
        </template>

        <!-- 其他信息 -->
        <el-collapse-item title="其他信息" name="other">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="form.remark"
                  type="textarea"
                  placeholder="请输入备注"
                  :rows="4"
                  :disabled="!isFieldEditable('remark')"
                  :readonly="isFieldReadonly"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>
      
      <!-- 审批进度组件 -->
      <div v-if="form.approvalInfoId" style="margin-bottom: 20px">
        <approval-progress :approval-info-id="form.approvalInfoId" />
      </div>
      
      <el-form-item
        label="审核意见"
        prop="approvalRemark"
        style="margin-bottom: 0"
        v-if="form.approvalStatus === 'rejected'"
      >
        <el-input
          v-model="form.approvalRemark"
          disabled
          type="textarea"
          placeholder="请输入审核意见"
          :rows="3"
          style="width: 100%"
          :readonly="isFieldReadonly"
        ></el-input>
      </el-form-item>
    </el-form>
    <el-row style="margin-top: 20px">
      <el-col :span="24">
        <!-- 详情模式按钮 -->
        <template v-if="isDetailMode">
          <el-button @click="goBack">返 回</el-button>
        </template>

        <!-- 审批模式下的审核意见字段 -->
        <div
          v-else-if="operationType === 'approve'"
          style="margin-bottom: 20px"
        >
          <el-form-item
            label="审核意见"
            prop="approvalRemark"
            style="margin-bottom: 0"
          >
            <el-input
              v-model="form.approvalRemark"
              type="textarea"
              placeholder="请输入审核意见"
              :rows="3"
              style="width: 100%"
              :readonly="isFieldReadonly"
            ></el-input>
          </el-form-item>
          <el-button
            type="success"
            @click="handleApprovePass"
            :loading="approvePassLoading"
            :disabled="approvePassLoading"
            style="margin-top: 10px; margin-right: 10px"
            >通 过</el-button
          >
          <el-button
            type="danger"
            @click="handleApproveReject"
            :loading="approveRejectLoading"
            :disabled="approveRejectLoading"
            style="margin-top: 10px; margin-right: 10px"
            >驳 回</el-button
          >
          <el-button @click="goBack" style="margin-top: 10px">取 消</el-button>
        </div>

        <!-- 普通编辑模式按钮 -->
        <template v-else>
          <el-button
            type="primary"
            @click="submitForm"
            :loading="submitLoading"
            :disabled="submitLoading"
            style="margin-right: 10px"
            >确 定</el-button
          >
          <el-button
            v-hasRole="[
              'student',
              'enterprise_depart_admin',
              'enterprise_unit_admin',
            ]"
            v-if="
              form.approvalStatus === 'no_submit' ||
              form.approvalStatus === 'rejected'
            "
            type="primary"
            @click="saveAndSubmit"
            :loading="saveSubmitLoading"
            :disabled="saveSubmitLoading"
            style="margin-right: 10px"
            >保存并提交</el-button
          >
          <el-button @click="goBack">取 消</el-button>
        </template>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="StudentEdit">
import { getDetail, editItem, addItem } from "@/api/student";
import { getRegionTree } from "@/api/common";
import { submitApproval, handleApproval } from "@/api/approval";
import { getTrainingUnitList, getPracticeDeptList } from "@/api/system/dept";
import ImageUpload from "@/components/ImageUpload/index.vue";
import ApprovalProgress from "@/components/ApprovalProgress";
import useUserStore from "@/store/modules/user";
import { isPhone } from "@/utils/index";

const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
const {
  sys_user_sex,
  nation,
  political_status,
  specialty,
  training_category,
  university,
  graduate_education_system,
  train_progress,
  sys_yes_no,
} = proxy.useDict(
  "sys_user_sex",
  "nation",
  "political_status",
  "specialty",
  "training_category",
  "university",
  "graduate_education_system",
  "train_progress",
  "sys_yes_no"
);

const userId = ref(route.params.userId);
const operationType = ref(route.query.type || "edit"); // edit, approve, detail
const isDetailMode = ref(operationType.value === "detail");

const form = ref({});
const activeCollapseItems = ref(["basic"]);
const previewAge = ref(0);
const previewBirthday = ref("");
const submitLoading = ref(false);
const saveSubmitLoading = ref(false);
const approvePassLoading = ref(false);
const approveRejectLoading = ref(false);

const regionOptions = ref([]);
const trainingUnitList = ref([]);
const practiceDeptList = ref([]);

const cascaderProps = {
  value: "extId",
  label: "extName",
  children: "children",
  expandTrigger: "hover",
};

// 字段权限配置
const fieldPermissions = {
  enterprise_group_admin: {
    editable: true,
    fields: "all",
  },
  admin: {
    editable: true,
    fields: "all",
  },
  student: {
    editable: true,
    fields: [
      "sex",
      "nation",
      "idCard",
      "phonenumber",
      "email",
      "origin",
      "political",
      "birthday",
      "emergencyContact",
      "emergencyPhonenumber",
      "avatar",
      "graduateUniversity",
      "graduateCollege",
      "graduateMajor",
      "graduateStartEnd",
      "masterUniversity",
      "masterCollege",
      "masterMajor",
      "masterStartEnd",
      "remark",
    ],
    readonlyFields: [
      "nickName",
      "trainField",
      "trainType",
      "trainUniversity",
      "trainDeptId",
      "trainMajor",
      "trainStartDate",
      "trainYear",
      "trainStartEnd",
      "trainStatus",
      "graduateStay",
      "practiceDeptId",
      "practiceAddress",
      "joinStartDate",
      "joinEntDate",
      "joinEntTopicName",
      "joinEntTopicIntroduction",
    ],
  },
  enterprise_unit_admin: {
    editable: true,
    fields: "all",
    readonlyFields: [
      "nickName",
      "trainField",
      "trainType",
      "trainUniversity",
      "trainStartDate",
      "trainDeptId",
      "practiceAddress",
    ],
  },
  enterprise_depart_admin: {
    editable: true,
    fields: "all",
    readonlyFields: [
      "nickName",
      "trainField",
      "trainType",
      "trainUniversity",
      "trainStartDate",
      "trainDeptId",
      "practiceAddress",
    ],
  },
};

const checkKeyList = [
  "trainCollege",
  "trainMajor",
  "trainYear",
  "trainStartEnd",
  "trainStatus",
  "graduateStay",
  "joinStartDate",
  "joinEntDate",
  "joinEntTopicName",
  "joinEntTopicIntroduction",
];

const isFieldReadonly = computed(() => {
  return isDetailMode.value;
});

// 检查字段是否可编辑
const isFieldEditable = (fieldName) => {
  if (isDetailMode.value) {
    return false;
  }

  const currentRole = getCurrentUserRole();
  if (
    fieldName === "idCard" &&
    currentRole === "student" &&
    form.value?.approvalStatus === "approved"
  ) {
    return false;
  }
  const permission = fieldPermissions[currentRole];

  if (!permission || !permission.editable) {
    return false;
  }

  if (
    permission.readonlyFields &&
    permission.readonlyFields.includes(fieldName)
  ) {
    return false;
  }

  if (permission.fields === "all") {
    return true;
  }

  return permission.fields.includes(fieldName);
};

// 获取当前用户角色
const getCurrentUserRole = () => {
  const userStore = useUserStore();
  return userStore.roles?.[0] || "student";
};

// 计算出生日期和年龄
const calculateBirthInfo = (idCard) => {
  if (!idCard || idCard.length !== 18) {
    return { birthday: "", age: "" };
  }

  const year = idCard.substring(6, 10);
  const month = idCard.substring(10, 12);
  const day = idCard.substring(12, 14);

  const birthday = `${year}-${month}-${day}`;
  const today = new Date();
  const birthDate = new Date(year, month - 1, day);
  const age = today.getFullYear() - birthDate.getFullYear();

  return { birthday, age };
};

// 根据身份证号变化更新出生日期和年龄
const handleIdCardChange = () => {
  if (form.value.idCard) {
    const { birthday, age } = calculateBirthInfo(form.value.idCard);
    previewAge.value = age;
    previewBirthday.value = birthday;
  }
};

// 加载地区数据
const loadRegionData = async () => {
  try {
    const response = await getRegionTree();
    regionOptions.value = response.data;
  } catch (error) {
    console.error("加载地区数据失败:", error);
    proxy.$modal.msgError("加载地区数据失败");
  }
};

// 获取培养单位列表
const queryTrainingUnitList = () => {
  getTrainingUnitList().then((res) => {
    trainingUnitList.value = res.data;
  });
};

// 处理培养单位变化
const handleTrainDeptChange = (val) => {
  if (!val) {
    practiceDeptList.value = [];
    return;
  }
  getPracticeDeptList(val).then((res) => {
    practiceDeptList.value = res.data;
  });
};

// 加载学生数据
const loadStudentData = async () => {
  try {
    const response = await getDetail(userId.value);
    form.value = {
      ...response.data,
      practiceAddress: response.data.practiceAddress
        ? response.data.practiceAddress.split(",")
        : [],
      approvalRemark:
        operationType.value === "approve"
          ? ""
          : response.data.approvalRemark || "",
    };
    handleIdCardChange();
    handleTrainDeptChange(response.data.trainDeptId);
  } catch (error) {
    console.error("加载学生数据失败:", error);
    proxy.$modal.msgError("加载学生数据失败");
    goBack();
  }
};

// 提交表单
const submitForm = () => {
  if (submitLoading.value) return;

  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
      submitLoading.value = true;
      const params = {
        ...form.value,
        practiceAddress: form.value.practiceAddress.join(","),
      };
      editItem(params)
        .then(() => {
          proxy.$modal.msgSuccess("修改成功");
          goBack();
        })
        .catch((error) => {
          console.error("修改失败:", error);
        })
        .finally(() => {
          submitLoading.value = false;
        });
    } else {
      proxy.$modal.msgError("请填写必填项");
    }
  });
};

// 保存并提交
const saveAndSubmit = () => {
  if (saveSubmitLoading.value) return;

  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
      if (checkKeyList.some((key) => !form.value[key])) {
        proxy.$modal.msgError("请填写完所有信息后再提交");
        return;
      }
      saveSubmitLoading.value = true;
      const params = {
        ...form.value,
        practiceAddress: form.value.practiceAddress.join(","),
      };
      editItem(params)
        .then(() => {
          proxy.$modal.msgSuccess("修改成功");
          submitApproval({
            businessId: form.value.userId,
            approvalTypeCode: "student_infor_flow",
            approvalInfo: JSON.stringify(form.value)
          });
          goBack();
        })
        .catch((error) => {
          console.error("保存并提交失败:", error);
        })
        .finally(() => {
          saveSubmitLoading.value = false;
        });
    } else {
      proxy.$modal.msgError("请填写必填项");
    }
  });
};

// 通过审批
const handleApprovePass = () => {
  if (approvePassLoading.value) return;

  approvePassLoading.value = true;
  const approvalData = {
    approvalInfoId: form.value.approvalInfoId,
    approvalNodeId: form.value.approvalNodeId,
    approvalStatus: "approved",
    remark: form.value.approvalRemark,
  };

  handleApproval(approvalData)
    .then(() => {
      proxy.$modal.msgSuccess("审批通过");
      goBack();
    })
    .catch((error) => {
      console.error("审批通过失败:", error);
    })
    .finally(() => {
      approvePassLoading.value = false;
    });
};

// 驳回审批
const handleApproveReject = () => {
  if (!form.value.approvalRemark) {
    proxy.$modal.msgError("请填写审核意见");
    return;
  }

  if (approveRejectLoading.value) return;

  approveRejectLoading.value = true;
  const approvalData = {
    approvalInfoId: form.value.approvalInfoId,
    approvalNodeId: form.value.approvalNodeId,
    approvalStatus: "rejected",
    remark: form.value.approvalRemark,
  };

  handleApproval(approvalData)
    .then(() => {
      proxy.$modal.msgSuccess("已驳回");
      goBack();
    })
    .catch((error) => {
      console.error("审批驳回失败:", error);
    })
    .finally(() => {
      approveRejectLoading.value = false;
    });
};

// 返回上一页
const goBack = () => {
  router.back();
};

const getProgressStatusLabel = (status) => {
  const dict = train_progress.find((item) => item.value === status);
  return dict ? dict.label : status;
};

const rules = computed(() => {
  const userStore = useUserStore();
  if (userStore.roles?.includes("student")) {
    return {
      userName: [
        { required: true, message: "账号不能为空", trigger: "blur" },
        {
          min: 2,
          max: 20,
          message: "账号长度必须介于 2 和 20 之间",
          trigger: "blur",
        },
      ],
      nickName: [{ required: false, message: "姓名不能为空", trigger: "blur" }],
      password: [
        { required: true, message: "用户密码不能为空", trigger: "blur" },
        {
          min: 5,
          max: 20,
          message: "用户密码长度必须介于 5 和 20 之间",
          trigger: "blur",
        },
        {
          pattern: /^[^<>"'|\\]+$/,
          message: "不能包含非法字符：< > \" ' \\ |",
          trigger: "blur",
        },
      ],
      phonenumber: [
        { required: true, message: "手机号码不能为空", trigger: "blur" },
        {
          pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          message: "请输入正确的手机号码",
          trigger: "blur",
        },
      ],
      email: [
        { required: true, message: "邮箱不能为空", trigger: "blur" },
        { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" },
      ],
      emergencyPhonenumber: [
        {
          required: true,
          message: "紧急联系人联系方式不能为空",
          trigger: "blur",
        },
        {
          pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          message: "请输入正确的紧急联系人手机号码",
          trigger: "blur",
        },
      ],
      origin: [{ required: true, message: "籍贯不能为空", trigger: "blur" }],
      emergencyContact: [
        { required: true, message: "紧急联系人不能为空", trigger: "blur" },
      ],
      avatar: [{ required: true, message: "照片不能为空", trigger: "change" }],
      graduateUniversity: [
        {
          required: true,
          message: "请选择本科毕业高校名称",
          trigger: "change",
        },
      ],
      graduateCollege: [
        {
          required: true,
          message: "本科毕业学院名称不能为空",
          trigger: "blur",
        },
      ],
      graduateMajor: [
        { required: true, message: "本科专业不能为空", trigger: "blur" },
      ],
      graduateStartEnd: [
        { required: true, message: "请选择本科毕业时间", trigger: "change" },
      ],
      masterUniversity: [
        {
          required: true,
          message: "请选择研究生毕业高校名称",
          trigger: "change",
        },
      ],
      masterCollege: [
        {
          required: true,
          message: "研究生毕业学院名称不能为空",
          trigger: "blur",
        },
      ],
      masterMajor: [
        { required: true, message: "研究生专业不能为空", trigger: "blur" },
      ],
      masterStartEnd: [
        { required: true, message: "请选择研究生毕业时间", trigger: "change" },
      ],
      sex: [{ required: true, message: "请选择性别", trigger: "change" }],
      nation: [{ required: true, message: "请选择民族", trigger: "change" }],
      political: [
        { required: true, message: "请选择政治面貌", trigger: "change" },
      ],
      idCard: [
        { required: true, message: "身份证号不能为空", trigger: "blur" },
        {
          pattern:
            /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
          message: "请输入正确的身份证号码",
          trigger: "blur",
        },
      ],
      trainStatus: [
        { required: false, message: "请选择培养阶段", trigger: "change" },
      ],
      trainField: [
        { required: false, message: "请选择培养领域", trigger: "change" },
      ],
      trainType: [
        { required: false, message: "请选择培养类别", trigger: "change" },
      ],
      trainUniversity: [
        { required: false, message: "请选择高校名称", trigger: "change" },
      ],
      trainYear: [
        { required: false, message: "请选择学制", trigger: "change" },
      ],
    };
  } else {
    return {
      trainCollege: [
        {
          required: false,
          message: "请输入工程硕博士学院名称",
          trigger: "change",
        },
      ],
      trainMajor: [
        {
          required: false,
          message: "请输入工程硕博士培养专业",
          trigger: "change",
        },
      ],
      trainYear: [
        { required: false, message: "请选择工程硕博士学制", trigger: "change" },
      ],
      trainStartEnd: [
        {
          required: false,
          message: "请选择工程硕博士毕业时间",
          trigger: "change",
        },
      ],
      trainStatus: [
        {
          required: false,
          message: "请选择工程硕博士培养阶段",
          trigger: "change",
        },
      ],
      graduateStay: [
        {
          required: false,
          message: "请选择毕业后是否留在中国一汽工作",
          trigger: "change",
        },
      ],
      joinStartDate: [
        { required: false, message: "请选择实践开始时间", trigger: "change" },
      ],
      joinEntDate: [
        { required: false, message: "请选择实践结束时间", trigger: "change" },
      ],
      joinEntTopicName: [
        { required: false, message: "请输入实践课题名称", trigger: "change" },
      ],
      joinEntTopicIntroduction: [
        { required: false, message: "请输入实践课题简介", trigger: "change" },
      ],
    };
  }
});

const handleGotoProgressDetail = (row) => {
  router.push({
    path: `/enterprise-practice-progress/edit/${row.id}`,
    query: { mode: "view", planDetailId: row.planDetailId },
  });
};

// 初始化
loadRegionData();
queryTrainingUnitList();
loadStudentData();
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
